相关疑难解决方法(0)

指向类成员的指针作为模板参数

是否可以使用非类型模板参数,它实际上是指向类成员的指针?我想要做的是如下:

struct Person {
  Dog dog;
};

template <?? ptr>
struct Strange {
  // ...
};

typedef Strange<&Person::dog> weird;
Run Code Online (Sandbox Code Playgroud)

到目前为止,我的工作让我相信没有任何类似的可能,但我很好奇是否有人可以说不然.

c++ templates pointers member

29
推荐指数
1
解决办法
1万
查看次数

是否可以模拟模板<auto X>?

它有可能吗?我希望它能够启用参数的编译时传递.假设它只是为了方便用户,因为人们可以随时输出真实类型template<class T, T X>,但是对于某些类型,即指向成员函数的指针,即使使用decltype快捷方式,它也非常繁琐.请考虑以下代码:

struct Foo{
  template<class T, T X>
  void bar(){
    // do something with X, compile-time passed
  }
};

struct Baz{
  void bang(){
  }
};

int main(){
  Foo f;
  f.bar<int,5>();
  f.bar<decltype(&Baz::bang),&Baz::bang>();
}
Run Code Online (Sandbox Code Playgroud)

是否有可能将其转换为以下内容?

struct Foo{
  template<auto X>
  void bar(){
    // do something with X, compile-time passed
  }
};

struct Baz{
  void bang(){
  }
};

int main(){
  Foo f;
  f.bar<5>();
  f.bar<&Baz::bang>();
}
Run Code Online (Sandbox Code Playgroud)

c++ templates type-inference

17
推荐指数
2
解决办法
3059
查看次数

使用constexpr和返回模板函数的C++ 0x错误

我试图找到问题C++模板非类型参数类型推导问题的解决方案,它不涉及调用f的模板参数,但隐式选择模板参数的正确类型.

由于constexpr应该保证函数只包含编译时常量,并且在编译时进行评估(至少这是我认为的那样),我认为它可能是这个问题的解决方案.所以我想出了这个:

template <class T, T VALUE> void f() {}

//first i tried this:
template <class T> auto get_f(T t) -> decltype( &f<T,t> ) { return f<T,t>; }

//second try:
template <class T> constexpr void (&get_f( T t ))()  { return f<T,t>; }

int main()
{
    get_f(10)(); //gets correct f and calls it
}
Run Code Online (Sandbox Code Playgroud)

第一个版本生成以下错误:

error: use of parameter 't' outside function body
Run Code Online (Sandbox Code Playgroud)

这真的令人困惑,因为在尾部返回类型的decltype语句中使用参数应该没问题?

第二个版本生成以下错误:

error: invalid initialization of non-const reference of type 'void (&)()' 
       from …
Run Code Online (Sandbox Code Playgroud)

c++ templates constexpr c++11

10
推荐指数
1
解决办法
1906
查看次数

指向struct/class的递归成员的指针的变量序列作为模板参数

我正在努力进行一些模板编程,希望你能给我一些帮助.我编写了一个C++ 11接口,给出了一些结构,如:

struct Inner{
  double a;
};
struct Outer{
  double x, y, z, r;
  Inner in;
};
Run Code Online (Sandbox Code Playgroud)

对实际数据实现getter/setter,该数据是为指定的struct成员定制的:

MyData<Outer, double, &Outer::x,
                               &Outer::y, 
                               &Outer::z,
                               &Outer::in::a //This one is not working
              > state();

Outer foo = state.get();
//...  
state.set(foo);
Run Code Online (Sandbox Code Playgroud)

我设法通过以下方式为简单结构实现此功能:

template <typename T, typename U, U T::* ... Ms>
class MyData{
   std::vector<U *> var;
  public:
    explicit MyData();
    void set(T const& var_);
    T get() const;
};

template <typename T, typename U, U T::* ... Ms>
MyData<T, U, Ms ... >::Struct():var(sizeof...(Ms))
{
}

template …
Run Code Online (Sandbox Code Playgroud)

c++ templates template-meta-programming variadic-templates c++11

9
推荐指数
1
解决办法
215
查看次数