如何在模板参数中检查模板模板类的类型?
示例
B<T>和C<T>是模板类。
我想要创建一个类D<class BC>,它可以是D<B>或D<C>。
只有D<B>有D::f()。
这是我的解决办法(演示)。它起作用了。
#include <iostream>
using namespace std;
class Dummy{};
template<class T>class B{};
template<class T>class C{};
template<template<class T> class BC>class D{
//f() is instantiated only if "BC" == "B"
public: template<class BCLocal=BC<Dummy>> static
typename std::enable_if<std::is_same<BCLocal,B<Dummy>>::value,void>::type f(){
}
//^ #1
};
int main() {
D<B>::f();
//D<C>::f(); //compile error as expected, which is good
return 0;
} #1的行非常长,很难看(使用Dummy进行黑客攻击)。
在实际程序中,它也很容易出错,特别是当B<...>和C<...>可以有5-7模板参数时.
有什么办法可以改进吗?
我的梦想是:-
template<class BCLocal=BC> static
typename std::enable_if<std::is_same<BCLocal,B>::value,void>::type f(){
}发布于 2017-05-08 08:39:53
为什么不直接将比较提取到一个方便的实用工具中呢?
#include <type_traits>
template<template<class...> class L, template<class...> class R>
struct is_same_temp : std::false_type {};
template<template<class...> class T>
struct is_same_temp<T, T> : std::true_type {};然后,f上的SFINAE可以简单地如下所示:
static auto f() -> typename std::enable_if<is_same_temp<BC, B>::value>::type {
}不需要为void指定enable_if,因为它是它提供的默认类型。
而后来者型也有美化效果,我想。
有了C++14,我们可以进一步美化。首先是可变模板。
template<template<class...> class L, template<class...> class R>
using bool const is_same_temp_v = is_same_temp<L, R>::value;然后使用std::enable_if_t模板别名:
static auto f() -> std::enable_if_t<is_same_temp_v<BC, B>> {
}https://stackoverflow.com/questions/43843114
复制相似问题