Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

Do c++ concepts cause template instantiations to be written to build output?

For libraries with many large and complex template instantiations, it seems to me that one of the major considerations in deciding whether to use concepts would be whether or not the build output is smaller in size.

With SFINAE, my understanding is that the following code will cause the template instantiations std::is_function<bar> and std::enable_if<true, bool> to be included in the build output, increasing its size (albeit marginally for this example):

#include <type_traits>

template<typename F,
         typename = std::enable_if_t<
                    std::is_function<F>::value,
         bool> = true>
void foo(F& f)
{
    // do some stuff with f
}

void g();

int main()
{
    foo(g);
    return 0;
}

If a C++20 concept based on std::is_function is used instead, obviously the template will have to be instantiated to check it. But is that instantiation then written to the final build output? And does this differ depending on compiler implementation?

#include <type_traits>

template<typename F>
concept Function = std::is_function<F>::value;

template<Function F>
void foo(F& f)
{
    // do some stuff with f
}
//...
question from:https://stackoverflow.com/questions/65927798/do-c-concepts-cause-template-instantiations-to-be-written-to-build-output

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems you are worried about code size.

Classes, and here I include instantiations of class templates, are just abstract pieces of information that the compiler knows about. They do not contribute to the code size.

Only functions, including member functions, contribute to code size. Member functions of class templates contribute to code size only when they are instantiated because the way in which they are used requires it (the C++ standard calls it "ODR-used").

In your examples, no member functions of std::is_function and std::enable_if are ODR-used, so they are not instantiated, and they do not contribute to code size.

But is that instantiation then written to the final build output?

No code is generated. But typically compilers write debugging information to the output. In that sense, something is written to the output.

And does this differ depending on compiler implementation?

As far as debugging information is concerned: yes. But whether an instantiation occurs is governed by the rules of the language, and there should not be a difference between compilers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...