vendredi 21 octobre 2016

What is the deduced type of a constexpr?

#include <iostream>
#include <string>

void foo(int& k) { std::cout << "int&\n"; }
void foo(int&& k) { std::cout << "int&&\n"; }
void foo(const int& k) { std::cout << "const int&\n"; }
void foo(const int&& k) { std::cout << "const int&&\n"; }    
int main() {
  static  constexpr int k = 1;
  foo(k);
  foo(1);
}

The output is:

const int&
int&&

What exactly is a constexpr variable treated as? The overload for foo gives const int&.

Edit: Moving on with constexpr being deduced as const T&;

Why does a constexpr at class scope fail to be passed to a function taking universal reference?!

#include <type_traits>

template <typename T>
void goo(T&& k) {
  static_assert(std::is_same<decltype(k), const int&>::value, "k is const int&");
}

class F {
  static  constexpr int k = 1;
public:
  void kk2 () { goo(k); }
};

int main () {
  F a;
  a.kk2();
}

The above fails to compile giving error undefined reference to F::k However the below passes:

#include <type_traits>

template <typename T>
void goo(T&& k) {
  static_assert(std::is_same<decltype(k), const int&>::value, "k is const int&");
}

int main() {
  static  constexpr int k = 1;
  goo(k);
}

Aucun commentaire:

Enregistrer un commentaire