Can I use decltype (or something similar) for explicit template instantiation without signature duplication?

假如想象 提交于 2019-12-04 09:51:15
5gon12eder

It actually works but the syntax is different:

template
decltype(foo<int>) foo<int>;

decltype gives you a type but the explicit instantiation requires a declaration which is a type followed by a name.

Tried with GCC 4.9.1; it works as expected and compiles without any warnings even with the -pedantic flag.

It's actually even simpler than @5gon12eder suggested:

template decltype(foo<int>) foo;

but yes, it's just like he said - decltype() only provides the type, and a signature is not really a type.

Edit: This doesn't work when the template has value arguments rather than just types, so if we have

template <typename T, unsigned Val> bar(T t);

then

template decltype(bar<int, 1>) bar;

will not compile, while

template decltype(bar<int, 1>) bar<int, 1>;

will.

No, because of overloading

template<typename T> void foo(T& t,
                     SomeType some_parameter,
                     AnotherType another_parameter,
                     EtcType yet_another_parameter,
                     AsYouCanTell this_is_a_very_long_signature);
template<template T> void foo(T& t); //completely unrelated function
template<template T> void foo(char); //another completely unrelated function

Now imagine, what is the minimum information required to explicitly instantiate the first one? Well, you need the full signature to disambiguate it, so

explicit int foo(int&, SomeType, AnotherType, EtcType, AsYouCanTell)

is the theoretical minimum amount of information. So what C++ requires actually has very little overhead:

template void foo<int>(int& t, SomeType, AnotherType, EtcType, AsYouCanTell);

If you don't want to type all that, then Konrad's suggestion of a macro is the way to go.

Konrad Rudolph

I think this is a good, legitimate use for a macro:

#define INSTANTIATE_FOO(type) \
    template void foo<type>(type& t, \
                  SomeType some_parameter, \
                  AnotherType another_parameter, \
                  EtcType yet_another_parameter, \
                  AsYouCanTell this_is_a_very_long_signature);

INSTANTIATE_FOO(int)
INSTANTIATE_FOO(float)
INSTANTIATE_FOO(my_little_dragon)

#undef INSTANTIATE_FOO
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!