Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

c++ - error C2971 a variable with non-static storage duration cannot be used as a non-type argument

Here is a simple example (the idea is to avoid a huge if..else or switch block inside a function):

namespace foo {
   enum class VALUES : int { val_0 = 0, val_1 = 1 };

   template<VALUES T>
   void print();

   template<>
   void print<VALUES::val_0>() { std::cout << "val_0
"; }

   template<>
   void print<VALUES::val_1>() { std::cout << "val_1
"; }

   void bar(int type) {
      VALUES v = static_cast<VALUES>(type);
      print<v>(); //error C2971 - "v" is a non-constant argument at compile-time
   }
};

The question is how to call print<...>() based on the bar's parameter? Please do not suggest to use if..else or switch.

question from:https://stackoverflow.com/questions/65952326/error-c2971-a-variable-with-non-static-storage-duration-cannot-be-used-as-a-non

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Templates are deduced at compile time. Which means that those template arguments are constant (at compile time). In your case, int type is not a constant type and so is VALUES v. In order to resolve v at compile time, you need to mark is as constexpr VALUES v; and which also means that you need to initialize it with values. In this case, with compile time resolvable values. That's why this works,

constexpr VALUES v = VALUES::val_0;
print<v>(); 

But not this,

VALUES m = VALUES::val_0;
constexpr VALUES v = m;    // As soon as you do this, it is no longer resolvable at compile time.
print<v>(); 

So the simplest answer is, you will have to use if/else, switch or templates to get it done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...