3

is_const式を関数に変換することは可能ですか、testそれともトップ レベルの cv-qualifiers がテンプレート型推論中に無視されるため、これは不可能ですか?

int main()
{
  using std::is_const;

  const int x = 0;
  int y = 0;

  // move to "bool test()"
  std::cout
    << "main, x: " << is_const<decltype(x)>::value << "\n"  // true
    << "main, y: " << is_const<decltype(y)>::value << "\n"  // false
    ;

  std::cout
    << "test, x: " << test(x) << "\n"  // false, I wanted true
    << "test, y: " << test(y) << "\n"  // false
    ;
}

次のようなさまざまなバージョンを試してみましたが、失敗しました。

template<typename T>
bool test(T x)
{
  return is_const<???>::value;
}

test私は何かが欠けていないこと、そしてそのような関数を書くことは本当に不可能であることを確認したい. (可能であれば、C++03 バージョンが可能かどうかも知りたいです。)

ご検討をお願いいたします

アップデート

Mankarse のおかげで、右辺値参照の場合は型推定が異なることを知りました。

template<typename T> void t1(T x);
template<typename T> void t2(T& x);
template<typename T> void t3(T&& x);

const int x = 42;
int y = 0;

t1(x);  // T = int:        t1<int>(int x)
t1(y);  // T = int:        t1<int>(int x)

t2(x);  // T = const int: t2<const int>(const int& x)
t2(y);  // T = int: t2<int>(int& x)

t3(x);  // T = const int&: t3<const int&>(const int& && x)
t3(y);  // T = int&:       t3<int&>(int& && x)
4

1 に答える 1

6

C++11 では、完全転送の右辺値参照を使用してこれを行うことができます。

template<typename T>
bool test(T&& x)
{
    return std::is_const<typename std::remove_reference<T>::type>::value;
}

C++03 では、代わりに左辺値参照を使用できます。

template<typename T>
bool test(T& x) {
    return boost::is_const<T>::value;
}

2 つの違いを以下に示します。

typedef int const intc;
intc x = intc();
int y = int();
std::cout                                     // C++11 C++03
  << "x: " << test(x) << "\n"                 // 1     1
  << "y: " << test(y) << "\n"                 // 0     0
  << "move(x): " << test(std::move(x)) << "\n"// 1     1 (when compiled as C++11)
  << "move(y): " << test(std::move(y)) << "\n"// 0     compilation error
  << "intc{}: " << test(intc()) << "\n"       // 0     compilation error
  << "int{}: " << test(int()) << "\n"         // 0     compilation error
;
于 2012-12-20T10:23:35.937 に答える