我想为一个类型和一个函数编写一个 MP 预测器。好像有什么不合法的地方:
#include <iostream>
template <class R>
struct X {
static constexpr int value = 0;
};
// Specialization for type
template <>
struct X<int(int)> {
static constexpr int value = 1;
};
// ERROR: Redefinition with diffrent kind
template <int (*F)(int)>
struct X {
static constexpr int value = 2;
};
int fun(int);
int main(int, char* [])
{
std::cout << "X<int>: " << X<int>::value << '\n';
std::cout << "X<int(int)>: " << X<int(int)>::value << '\n';
std::cout << "X<decltype(fun)>: " << X<decltype(fun)>::value << '\n';
std::cout << "X<fun>: " << X<fun>::value << '\n';
return 0;
}
是否有可能实现这样的目标?
更多详情: 有什么用?
- 学习元编程
- 编写一个通用预测器,它可以判断是否使用给定参数调用函数/对象实例(类似于 C++17 中的 is_callable)
最佳答案
Is it possible to achieve something like that?
您实际上是在询问是否可以重载类模板。你不能。
但是,你当然可以重载函数模板——你可以有一个函数模板,它接受一个非推导模板类型参数,特化它,然后有另一个函数模板接受一个非推导模板非类型参数:
#include <iostream>
template <class R> constexpr int X() { return 0; }
// specialization for type
template <> constexpr int X<int(int)>() { return 1; }
// Redefinition with different kind
template <int (*F)(int)>
constexpr int X() { return 2; }
int fun(int);
int main(int, char* [])
{
std::cout << "X<int>: " << X<int>() << std::endl;
std::cout << "X<int(int)>: " << X<int(int)>() << std::endl;
std::cout << "X<decltype(fun)>: " << X<decltype(fun)>() << std::endl;
std::cout << "X<fun>: " << X<fun>() << std::endl;
return 0;
}
根据需要打印 0、1、1 和 2。
关于c++ - 类型和非类型模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488319/