2016-11-15 5 views
2

最小/最大/ステップ機能と「constexprの関数の本体...ないリターン文」

$ g++ -std=c++11 test.cxx -o test.exe 
test.cxx: In instantiation of ‘static constexpr unsigned int MinMaxStep<min, max 
, step>::ValidValue(unsigned int) [with unsigned int min = 10u; unsigned int max 
= 100u; unsigned int step = 10u]’: 
test.cxx:22:40: required from here 
test.cxx:16:5: error: body of constexpr function ‘static constexpr unsigned int 
MinMaxStep<min, max, step>::ValidValue(unsigned int) [with unsigned int min = 10 
u; unsigned int max = 100u; unsigned int step = 10u]’ not a return-statement 
    } 
    ^

で使用される値の全て問題関数はテンプレートパラメータです。ファイルを保存しても値は変更されません。

これをconstexprの機能として表現することはできませんか?

私が何か間違っているとしたら、それは何ですか? ValidVaueconstexpr機能に変更するにはどうすればよいですか?


$ cat -n test.cxx 
1 #include <string> 
2 #include <iostream> 
3 
4 template <unsigned int min, unsigned int max, unsigned int step> 
5 class MinMaxStep 
6 { 
7 public: 
8  static constexpr unsigned int Min() { return min; } 
9  static constexpr unsigned int Max() { return max; } 
10  static constexpr unsigned int Step() { return step; } 
11  static constexpr unsigned int ValidValue(unsigned int v) 
12  { 
13   if (v <= min) { return min; } 
14   else if (v >= max) { return max; } 
15   return (v+step-1) - ((v+step-1)%step); 
16  } 
17 }; 
18 
19 int main (int argc, char* argv[]) 
20 { 
21  MinMaxStep<10, 100, 10> mms; 
22  unsigned int x = mms.ValidValue (18); 
23  std::cout << "value " << x << std::endl; 
24 
25  return 0; 
26 } 
+2

'return v <= min? (v + step-1)%step))); –

+0

3つの演算子を持つreturn文が1つ受け入れられました。すべてのメジャーコンパイラ(Clang、Comeau、GCC、ICC、MSVC、SunCC)の承認を受けていますか?それらのうちのいずれかがあなたが認識している半分の焼いた実装を持っていますか? – jww

答えて

5

constexpr関数の規則はC++ 11に非常に厳密でした。たとえば、returnという文だけがあります。ルールはC++でかなり緩和されました14。

詳細については、this constexpr referenceをご覧ください。

問題を解決するには、2つの方法があります。最も簡単な方法は、代わりにC++ 14を使用することです(コンパイラフラグを変更して-std=c++14を使用する)。もう1つの解決策は、ValidValue関数を3つの演算子を使用して1つのステートメント、returnステートメントのみをリファクタリングすることです。

+0

Lol ... C++ 14は問題になりません。私たちは時々特別な地獄に住んでいます。 Fedora 1およびWindows 2000のVisual Studio .NETでGCC 3をサポートしています。 – jww

+1

@jww:それでも 'constexpr'はまだあなたのための選択肢ですか? o_O – ildjarn

+0

@ildjarn - 'constexpr'は、' noexcept'や 'alignas'など他のキーワードと同様に[マクロで]抽象化することができます(https://github.com/weidai11/cryptopp/blob/master/ config.h#L923)。古いコンパイラで新しいフラグを受け入れることはできません:) – jww

関連する問題