【发布时间】:2018-05-14 14:43:43
【问题描述】:
抱歉标题含糊不清,我对问题的理解还不够好,甚至无法正确描述。我只是不明白为什么我的main() 的最后一行失败了。适量的嵌套模板调用如下:
#include <iostream>
template <typename T>
struct ObjFirst {};
template <typename T>
struct ObjFirst<void (*)(T)> {
template <void (*fp)(T)>
static void f(T arg){fp(arg);}
};
template <typename T, typename R>
struct ObjFirst<R (*)(T)> {
template <R (*fp)(T)>
static R f(T arg) {return fp(arg);}
};
template <typename T>
struct Id {
template <T fn_ptr>
static auto funcPtr(void) { return &ObjFirst<T>::template f<fn_ptr>; }
};
template <auto fn>
auto id() { return Id<decltype(fn)>::template funcPtr<fn>(); }
int sampleFunc(int) {return 0;}
void sampleFuncV(int) {}
template <typename R, typename T>
R sampleFuncT(T) {return R{};}
template <>
int sampleFuncT<int, int>(int i) {return 7+i;}
struct A {};
struct B : A {};
int main()
{
id<&sampleFunc>(); // OK
id<&sampleFuncV>(); // OK
auto f = id<&sampleFuncT<int, int>>(); // OK
std::cout << f(3); // Double-checking the result: OK ('10')
id<&std::dynamic_cast<B, A>>();
return 0;
}
你可以看到这个模板机制的几个不同的调用工作,但最后一个没有。有一刻我以为这是因为为模板化参数选择了错误的 ObjFirst 特化,但不是。
任何想法表示赞赏。使用 GCC 7、GCC 8 和 clang 6 可以观察到失败:https://godbolt.org/g/5spCJy
【问题讨论】:
标签: c++ templates gcc clang c++17