C++ 如何静态查询可能不存在的静态成员变量,提供默认值?
我正在编程一些类,通过C++ 如何静态查询可能不存在的静态成员变量,提供默认值?,c++,templates,constexpr,C++,Templates,Constexpr,我正在编程一些类,通过class模板参数将依赖项注入其中 在某些情况下,依赖类具有或可以具有声明其某些特定特征的静态constexpr成员。在下面的示例中,实现渲染器“概念”的类可以定义一个静态constexpr bool变量y\u axis\u bottom\u up,以指示它们期望垂直坐标向上增长 当然,我可以要求所有呈现器实现都提供这个布尔成员,但我更愿意在查询表达式中定义一个默认值 因为我需要使用这些信息来参数化进一步的模板,所以查询表达式必须是constexpr 当我找到答案时,我以为
class
模板参数将依赖项注入其中
在某些情况下,依赖类具有或可以具有声明其某些特定特征的静态constexpr成员。在下面的示例中,实现渲染器
“概念”的类可以定义一个静态constexpr bool变量y\u axis\u bottom\u up
,以指示它们期望垂直坐标向上增长
当然,我可以要求所有呈现器实现都提供这个布尔成员,但我更愿意在查询表达式中定义一个默认值
因为我需要使用这些信息来参数化进一步的模板,所以查询表达式必须是constexpr
当我找到答案时,我以为我已经找到了解决办法,但当我试图将它应用到我的需要时,我失败了
下面是我提出的非工作最小测试代码。第二个输出行应该是“1”,但两个输出都是“0”
任何帮助都将不胜感激
#include <iostream>
#include <type_traits>
template<class Config, typename = void>
struct vertical_axis_bottom_up
{
static constexpr bool value = false;
};
template<class Config>
struct vertical_axis_bottom_up<Config, decltype(Config::Renderer::y_axis_bottom_up)>
{
static constexpr bool value = Config::Renderer::y_axis_bottom_up;
};
struct Dummy_renderer {};
struct Config1
{
using Renderer = Dummy_renderer;
};
struct Dummy_renderer_2
{
static constexpr bool y_axis_bottom_up = true;
};
struct Config2
{
using Renderer = Dummy_renderer_2;
};
int main(int /*argc*/, char * /*argv*/[])
{
std::cout << "Default value for Config::Renderer::y_axis_bottom_up : " << vertical_axis_bottom_up<Config1>::value << std::endl;
std::cout << "Explicit value for Config::Renderer::y_axis_bottom_up: " << vertical_axis_bottom_up<Config2>::value << std::endl;
std::cout << "Press RETURN to terminate" << std::endl;
char ch; std::cin >> std::noskipws >> ch;
return -1;
}
#包括
#包括
模板
结构垂直轴底部向上
{
静态constexpr bool值=false;
};
模板
结构垂直轴底部向上
{
static constexpr bool value=Config::Renderer::y\u axis\u bottom\u up;
};
结构虚拟_渲染器{};
结构配置1
{
使用渲染器=虚拟渲染器;
};
结构虚拟渲染器2
{
静态constexpr bool y_轴底部向上=真;
};
结构配置2
{
使用渲染器=虚拟渲染器2;
};
int main(int/*argc*/,char*/*argv*/[])
{
std::cout这是在标准库中广泛实现的,allocator\u traits
就是一个很好的例子。下面是基本思想:
#include <iostream>
#include <type_traits>
template <class T, class = void>
struct MyTrait
{
static constexpr bool foo = false;
};
template <class T>
struct MyTrait<T, std::enable_if_t<std::is_same<const bool, decltype(T::foo)>::value>>
{
static constexpr bool foo = T::foo;
};
struct Class1 {
};
struct Class2 {
static constexpr bool foo = true;
};
int main()
{
std::cerr << MyTrait<Class1>::foo;
std::cerr << MyTrait<Class2>::foo;
}
#包括
#包括
模板
结构MyTrait
{
静态constexpr bool foo=false;
};
模板
结构MyTrait
{
静态constexpr bool foo=T::foo;
};
结构类别1{
};
结构类2{
静态constexpr bool foo=true;
};
int main()
{
标准::cerr@BaummitAugen:修复-谢谢you@BaummitAugen:应该把引语读到最后:-)我想不出重写的方法(例如通过继承),因此,我猜在不修改类的约束下,您可以选择检测成员的存在。我以为我已经尝试了该变体,但我显然犯了一个错误,因为它工作得很好。谢谢!