2016-04-18 53 views
3

我有一個模板類:模板的int參數C++ 11

template <int N> 
class Object<N> 
{ 
// ... 
} 

例如,我想打一個函數,它增加了裏面的東西,並返回類int N參數設置爲最大值其中:

template <int N1, int N2> 
Object<std::max(N1, N2)> AddObjects(const Object<N1> & object_1, const Object<N2> & object_2) 
{ 
    // ... 
} 

我必須做在C++ 11,但不幸的是沒有C++ 14(其中std::maxconstexpr)。在C++ 11中可能嗎?

+0

您仍然可以編寫自己的'constexpr'功能'max'。 – Jarod42

+0

@ Jarod42請問,如何在C++中編寫它11不能在constexpr函數中使用if-else? – vladon

+0

在C++ 11中,似乎需要三元運算符(我認爲'int' /'uint'的無分支版本有一些破解),在C++ 14中,'constexpr'規則允許其他:-) – Jarod42

回答

4

你可以改用三元運算符:

template <int N1, int N2> 
Object<(N1 > N2)? N1 : N2> AddObjects(const Object<N1> & object_1, const Object<N2> & object_2) { 
     // ... 
} 
+0

哇!從來沒有想過這樣的事情是可能的 – vladon