LoginSignup
2
1

More than 5 years have passed since last update.

関数の引数がT * const&とT const* const&では結果が変わるという話

Last updated at Posted at 2016-05-25

関数の引数がT * const&とT const* const&では結果が変わるという話

コード

#include <iostream>

template <typename T>
void f(T const&)
{
  std::cout << "f<T>()" << std::endl;
}
template <typename T>
void f(T const* const&)
{
  std::cout << "f<T*>()" << std::endl;
}

template <typename T>
void g(T const&)
{
  std::cout << "g<T>()" << std::endl;
}
template <typename T>
void g(T * const&)
{
  std::cout << "g<T*>()" << std::endl;
}

int main()
{
  int a{0};
  f(a);
  f(&a);
  g(a);
  g(&a);

  std::cout << std::endl;

  int const b{0};
  f(b);
  f(&b);
  g(b);
  g(&b);
}

実行結果

f<T>()
f<T>()
g<T>()
g<T*>()

f<T>()
f<T*>()
g<T>()
g<T*>()

まとめ

特に何も考えずにconstつけててハマった
どこにでもconstを付けてると望んだ実行結果にならないこともある

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1