给出像
这样的特征基类template<typename T>
class Trait {
public:
const bool isCapableOfSomething = false;
static void doSomething() {
// Raise compile time error here
}
};
我想知道如果有人试图用特征尚未专门用于的类型调用doSomething()
,如何引发错误。
我在Stackoverflow上出现了1000个解决方案。在其他变体中,大多数解决方案在不同程度上使用static_assert
s或SFINAE。然而,在遵循这些解决方案和实验的同时,我想出了以下小片段:
template<typename T>
class Trait {
public:
const bool isCapableOfSomething = false;
static void doSomething() {
(void) Error::This_trait_is_not_capable_of_doing_something();
}
private:
template<typename X>
struct Error { };
};
与大多数基于SFINAE的解决方案相比,这很容易理解((void)
甚至可以删除),它不依赖于static_assert
或由...提供的变通方法。 boost(不幸的是,static_assert
在我需要的任何地方仍然不受支持)并且它生成一个紧凑的错误消息
'This_trait_is_not_capable_of_doing_something' is not a member of 'Trait<SomeType>::Error<SomeType>'
(void) Error<T>::This_trait_is_not_capable_of_doing_something();
现在我只是想知道这是否是有效的C ++还是我错过了一些警告。