比如有一个模板类:
template<typename A, typename B>
class Example;
如果一对 (A, B) 被特化,那么其他类型就不能特化 A。例如,允许 (B, C),但不允许 (A, C)。
Example<int, double> E1, E2, E3; // OK
Example<int, double> E4; // OK
Example<int, bool> E5; // Not Allowed (Because <int, double> already exists)
Example<bool, double> E6; // OK
Example<double, double> E7; // OK
Example<double, int> E8; // Not Allowed (<double, double> already exists)
我尝试在运行时在模板参数 A 和 B 之间使用 std::map,但是是否有办法在编译期间执行此操作?喜欢 SFINAE 或其他技术吗?
我能想到的唯一真正的方法是不使其成为两个模板参数,而是提供到第二种类型的固定映射:
template <typename T>
struct ExampleAssociated { static_assert(false, "must specialize this"); };
template <typename A>
class Example {
using B = typename ExampleAssociated<A>::type;
};
template <>
struct ExampleAssociated<int> { using type = double; };
template <>
struct ExampleAssociated<bool> { using type = double; };
// ...
Example<int> E1; // OK
Example<bool> E6; // OK