简体   繁体   English

std :: normal_distribution的类型取决于模板

[英]Type of std::normal_distribution depending on template

Rarely T can be int and it will hang at: 很少T可以是int,它将挂在:

std::normal_distribution<T> distribution(0.0, 0.1);

This will be used in the next lines of my function and I wouldn't like to have an if/else with all the lines of code that depend on that. 这将在函数的下一行中使用,而我不希望所有与此相关的代码行都具有if / else。 As a result I am trying to do this: 结果,我正在尝试这样做:

#include <random>

#define T int

int main ()
{
  std::normal_distribution<((std::is_same<T, int>::value) ? (float) : (T))> distribution (0.0, 1$

  return 0;
}

and I am getting these errors: 我收到这些错误:

Georgioss-MacBook-Pro:Code gsamaras$ g++ -std=c++0x main.cpp 
main.cpp:7:69: error: expected expression
  std::normal_distribution<((std::is_same<T, int>::value) ? (float) : (T))> distribution ...
                                                                    ^
main.cpp:7:74: error: expected expression
  std::normal_distribution<((std::is_same<T, int>::value) ? (float) : (T))> distribution ...
                                                                         ^
main.cpp:7:77: error: C++ requires a type specifier for all declarations
  std::normal_distribution<((std::is_same<T, int>::value) ? (float) : (T))> distribution ...
                                                                            ^
3 errors generated.

Any idea on how to fix this or an alternative? 关于如何解决此问题或替代方案的任何想法?

#include <random>
#include <type_traits>

template<class T>
struct X
{
    using float_t = typename 
        std::conditional<std::is_floating_point<T>::value, T, double>::type;
    std::normal_distribution<float_t> dist{0.0, 0.1};
};

int main() {
    X<int> x;
    X<float> y;
    return 0;
}

std::conditional is the solution here: std :: conditional是这里的解决方案:

#include <random>

#define T int

int main ()
{
  std::normal_distribution<typename  std::conditional<std::is_same<T, int>::value, float, T>::type> dist(0.0, 1.0);
  return 0;
}

which says that if T is an int, then give float as the type of distribution, otherwise give T. 这表示如果T是一个整数,则给定float作为分布类型,否则给T。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM