【发布时间】:2016-10-21 12:22:43
【问题描述】:
#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);
}
输出是:
const int&
int&&
constexpr 变量究竟被视为什么?
foo 的重载为 const int&。
编辑:继续将 constexpr 推导出为 const T&;
为什么类范围内的 constexpr 无法传递给采用通用引用的函数?!
#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();
}
以上编译失败,报错undefined reference to F::k
但是以下通过:
#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);
}
【问题讨论】:
-
@GuillaumeRacicot 我认为这句话是指
goo(T&& k)。
标签: c++ c++11 templates overloading constexpr